<?php

namespace app\common\model\mysql;

use app\common\business\DataAuth;
use think\Model;

class SCategory extends Model
{
    /**
     * 自动生成写入时间
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 新增前
     * @param $model
     * @return mixed|void
     */
    protected static function onBeforeInsert($model){
        $userData = (new DataAuth())->getUserDetails();
        $model->create_by = $userData['userName'];
    }

    /**
     * 更新前
     * @param $model
     * @return mixed|void
     */
    protected static function onBeforeUpdate($model)
    {
        $userData = (new DataAuth())->getUserDetails();
        $model->update_by = $userData['userName'];
    }

    /**
     * 查询分类列表
     * @param $where
     * @param $field
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getNormalCategoryList($where, $field){
        $order = [
            "parent_id" =>"asc",
            "order_num" =>"asc",
        ];
        $result = $this->where($where)->field($field)->order($order)->select();

        return $result;
    }

    public function getCategoryTree($where,$field){
        $order = [
            "order_num" =>"asc",
        ];
        $result = $this->where($where)->field($field)->order($order)->select();
        return $result;
    }

    public function getCategoryByNameModel($category_name,$parent_id,$category_id){
        if(empty($category_name)){
            return false;
        }
        $where = [
            "category_name" =>$category_name,
            "parent_id"=>$parent_id,
            "del_flag"=>0,
        ];
        if($category_id){
            $result = $this->where("category_id", "<>", $category_id)->where($where)->find();
        }else{
            $result = $this->where($where)->find();
        }
        return $result;
    }

    /**
     * 根据id获取分类信息
     * @param $id
     * @return SysDictData|array|false|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryIdData($id){
        if(empty($id)){
            return false;
        }
        $where = [
            "category_id" =>$id,
        ];
        $result = $this->where($where)->find();
        return $result;
    }

    /**
     * 删除参数数据信息
     * @param $ids
     * @return bool
     */
    public function DeleteCategoryIds($ids){
        if(empty($ids)){
            return false;
        }
        $where = [
            ['category_id', '=', $ids]
        ];
        $data = [
            'del_flag'=>'2'
        ];
        $result = $this->where($where)->find()->save($data);
        return $result;
    }

    /**
     * 获取无限极分类列表
     * @param int $parentId
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryTreeChildren(int $parentId = 0, array $where = [])
    {
        // 初始化查询条件
        $map = [
            ['parent_id', '=', $parentId],
            ['del_flag', '=', 0],
        ];
        // 如果提供了额外的where条件，则合并它们
        if (!empty($where)) {
            $map[] = ['category_id', 'in', $where];
        }
        $categories = $this->where($map)->order('order_num', 'asc')->field("category_id as value,category_name as label")->select()->toArray();
        // 递归构建树形结构
        $tree = [];
        foreach ($categories as &$category) {
            // 递归获取子分类
            $category['children'] = $this->getCategoryTreeChildren($category['value'],$where);
            // 如果子分类为空，则删除 'children' 键
            if (empty($category['children'])) {
                unset($category['children']);
            }
            // 将当前分类添加到树中
            $tree[] = &$category;
        }
        // 注意：由于使用了引用，需要取消引用以避免潜在的问题
        unset($category);
        return $tree;
    }

    // 定义关联方法：每个分类都属于一个父级分类（除了顶级分类）
    public function parent()
    {
        return $this->belongsTo(SCategory::class, 'parent_id', 'category_id');
    }

    public function getCategoryByNamesModel($categoryIds){
        if(empty($categoryIds)){
            return false;
        }
        $categories = $this->whereIn("category_id", $categoryIds)
            ->with('parent') // 假设您已经定义了parent关系
            ->field("category_id, parent_id, category_name")
            ->select()->toArray();
        $categoryNames = [];
        foreach ($categories as $category) {
            $name = $category['category_name'];
            if ($category['parent_id'] > 0) {
                // 假设每个分类只有一个父级，这里获取父级名称
                // 注意：这里假设parent关系已经通过模型定义并加载了父级分类的数据
                $parentName = $category['parent'] ? $category['parent']['category_name'] : '';
                $name = "$parentName/$name"; // 或者使用其他格式来表示层级关系
            }
            $categoryNames[] = $name; // 将每个分类名称添加到数组中
        }
        return implode(',', $categoryNames); // 使用逗号作为分隔符返回所有名称
    }

    /**
     * 前端获取无限极分类列表
     * @param int $parentId
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryTreeChildrenFrontEnd(int $parentId = 0)
    {
        // 初始化查询条件
        $map = [
            ['parent_id', '=', $parentId],
            ['del_flag', '=', '0'],
            ['status', '=', '0'],
        ];
        $categories = $this->where($map)->order('order_num', 'asc')->field("category_id,category_name,category_img")->select()->toArray();
        // 递归构建树形结构
        $tree = [];
        foreach ($categories as &$category) {
            // 递归获取子分类
            $category['children'] = $this->getCategoryTreeChildrenFrontEnd($category['category_id']);
            // 如果子分类为空，则删除 'children' 键
            if (empty($category['children'])) {
                unset($category['children']);
            }
            // 将当前分类添加到树中
            $tree[] = &$category;
        }
        // 注意：由于使用了引用，需要取消引用以避免潜在的问题
        unset($category);
        return $tree;
    }

    public function getCategoryIdsArrModel($where,$field){
        $categoryIdsArr = $this->where($where)->column($field);
        return $categoryIdsArr;
    }
}
